class MyPage extends BaseList {
    constructor(action, orderby, flag, $pagesize, $pagination, cokiePageSize, cokiePageIndex, cokieListResult, listUrl, delUrl) {
        super(action, orderby, flag, $pagesize, $pagination, cokiePageSize, cokiePageIndex, cokieListResult, listUrl, delUrl);
    }
    GetFilter() {
        let item = super.GetFilter(0);
        item["ItemName"] = $.trim($("#ItemName").val()).length > 0 ? $.trim($("#ItemName").val()) : null;

        return JSON.stringify(item);
    }
    FetchAll() {
        $("#UomName").val("");
        this.FetchForPage(1);
    }
    EmptyTableContent() {
        $("#tabData01 tbody").empty();
    }
    SetTableContent(result) {
        $("#tabData01 tbody").empty();
        let content_01 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;  // 设置表格中checkbox的数量为表格的行数
        for (let i = 0; i < result.length; i++) {
            let id = result[i].itemId;
            content_01 += '<tr _mash_id="' + id + '">';
            content_01 += '<td style="vertical-align:middle;"><label style="margin-left:3px;" class="btn" for="R-' + id + '"><input id="R-' + id + '" name="_check_row" type="checkbox" onclick="_Instance.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + id + '"/><i></i><span></span></label></td>';
            content_01 += '<td style="text-align:center;">' + result[i].orderNo + '</td>';
            content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_Instance.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td class="edited-cell">' + result[i].itemName + '</td>';
            content_01 += '</tr>';

            $("#tabData01 tbody").append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabData01");

        let id = "cell__field";
        let name = "_cell__field";
        $('#tabData01 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        let _this = this;
        // 拖动表格行改变显示顺序
        $("#tabData01 tbody").wxdragsort({
            dragWrapper: $("#tabData01"),
            placeHolderWrapper: $("#tabData01"),
            parentobj: $("#tabData01"),
            dragColumnIndex: 1,
            dragEnd: function () {
                _this.UpdateLinesOrder();
            }
        });

        this.AutoAdjustTableHeightForLines();   // 自适应高度设置
        $(window).resize();                     // 防止因为出现滚动条而造成画面显示问题
        $('#loading').hide();
    }
    // 得到主产品计划项目明细
    GetLinesData() {
        let jsonInsert = [];
        let jsonUpdate = [];
        let itemResult = {};
        let jsonResult = [];
        // 得到修改过数据
        $('#tabData01 tbody').find("tr").each(function () {
            let _OrderNo = $.trim($(this).find('td').eq(1).text()) === '' ? null : $.trim($(this).find('td').eq(1).text());   // 编号即顺序号
            let _ItemName = $.trim($(this).find('td').eq(3).text()) === '' ? null : $.trim($(this).find('td').eq(3).text());  // 主产品计划项目名称
            if ($(this).find("td.dirty").length) {
                let item = {};
                let $row = $(this);

                item['itemId'] = parseInt($row.attr("_mash_id"));
                item['orderNo'] = _OrderNo;
                item['itemName'] = _ItemName;
                item['createdBy'] = parseInt($("#UserId").val());
                item['updatedBy'] = parseInt($("#UserId").val());

                if (parseInt($row.attr("_mash_id")) === 0) {
                    jsonInsert.push(item);
                } else {
                    jsonUpdate.push(item);
                }
            }
        });
        itemResult['insertList'] = jsonInsert;
        itemResult['updateList'] = jsonUpdate;
        jsonResult.push(itemResult);

        return itemResult;
    }
    DoInsert() {
        this.InsertNewLines();
    }
    // 保存
    DoSave() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        //step 2、执行处理
        if (this.GetLinesData().insertList.length > 0 || this.GetLinesData().updateList.length > 0) {
            super.DoAjax(this.GetLinesData(), "/master/mps_item/save.html", function (data, $self) {
                if (data.ItemList !== undefined) {
                    $self.SetTableContent(data.ItemList);
                    ShowSuccessMessagePanel("保存成功。");
                }
            });
        }
    }
    DoDelete($self) {
        let _params = {};
        _params['ItemId'] = $self.parent().parent().attr("_mash_id");
        _params['ItemName'] = $self.parent().parent().find("td").eq(3).text();
        _params['DeletedBy'] = $("#UserId").val();

        super.DoDelete(_params, ($self, data) => {
            if (data.ItemList !== undefined) {
                $self.SetTableContent(data.ItemList);
                ShowSuccessMessagePanel("删除成功。");
            }
        });
    }
    // 添加新行以及新行的操作方式
    InsertNewLines() {
        let $newLine = $('<tr class="newLine" _mash_id="0">' +
                '    <td></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="_Instance.RemoveNewLine($(this))"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');
        $('#tabData01 tbody').prepend($newLine);   // 加在前面
        this.rows = this.rows + 1;

        setOneTableRowColor("tabData01");
        this.AutoAdjustTableHeightForLines();  // 自适应高度设置

        let id = "cell__field";
        let name = "_cell__field";
        $newLine.find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });
    }
    RemoveNewLine($self) {
        showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', () => {
            $self.parent().parent().remove();
            this.rows = this.rows - 1;
            // 自适应高度设置
            this.AutoAdjustTableHeightForLines();
        });
    }
    UpdateLinesOrder() {
        // 设置拖动后的每行序号
        $("#tabData01 tbody").find("tr").each(function (index) {
            $(this).find("td").eq(1).text(index + 1);
        });

        let itemList = [];
        $('#tabData01 tbody').find("tr").each(function (index) {
            let _OrderNo = $.trim($(this).find('td').eq(1).text());   // 顺序号

            let item = {};
            item['itemId'] = parseInt($(this).attr("_mash_id"));
            item['orderNo'] = parseInt(_OrderNo);
            item['updatedBy'] = parseInt($("#UserId").val());
            itemList.push(item);
        });
        super.DoAjax(itemList, "/master/mps_item/updateLinesOrder.html", (data, $self) => {
            ShowSuccessMessagePanel("更改顺序成功。");
        });
    }
    ChoiceUser() {
        showModal(1295, 538, '选择用户', parent.basePath + '/master/employee/choice.html?flag=0', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            if (parent.choice_success) {
                $("#MemberId").val(parent.arrChoice[0][0]);
                $("#MemberName").val(parent.arrChoice[0][1]);
                // 取得该用户权限
                super.DoAjax(parent.arrChoice[0][0], "/master/mps_item/fetchAllByUser.html", (data, $self) => {
                    $("input[type='checkbox'][name='_check_row']").prop("checked", false);
                    $('#tabData01 tbody').find("tr").each(function () {
                        $(this).removeClass("row__selected");
                        // 设置删除按钮有效
                        let _event_delete_onclick = '_Instance.DoDelete($(this))';
                        $(this).children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
                    });
                    for (let i = 0; i < data.length; i++) {
                        let $obj = $("#R-" + data[i].itemId);
                        $obj.click();
                    }
                });
            }
            // 清空选择的数据
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    SetRule() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要设置的产品计划。");
            return false;
        }

        showModal(1295, 538, '产品计划项目使用授权', parent.basePath + '/master/employee/choice.html?flag=1', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            if (parent.choice_success) {
                this.GrantPermission(parent.arrChoice[0]);
            }
            // 清空选择的数据
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    SetRuleForSingle() {
        if ($("#MemberName").val() === "") {
            ShowErrorMessagePanel('请选择一个要授权的成员用户。');
            return;
        }
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要设置的产品计划。");
            return false;
        }
        let _result = [];
        let item = {};
        item['EmployeeId'] = $("#MemberId").val();
        _result.push(item);
        this.GrantPermission(_result);
    }
    GrantPermission(userList) {
        let _result = [];
        $("input[type='checkbox'][name='_check_row']:checked").each(function () {
            for (let i = 0; i < userList.length; i++) {
                let item = {};
                item['itemId'] = $(this).val();
                item['userId'] = userList[i].EmployeeId;
                item['updatedBy'] = $.trim($("#UserId").val());
                _result.push(item);
            }
        });
        // 授权
        super.DoAjax(_result, "/master/mps_item/grant.html", (data, $self) => {
            if (data > 0) {
                ShowSuccessMessagePanel("授权成功。");
            }
        });
    }
    Revoke() {
        if ($("#MemberName").val() === "") {
            ShowErrorMessagePanel('请选择一个用户。');
            return;
        }
        super.DoAjax($("#MemberId").val(), "/master/mps_item/revoke.html", (data, $self) => {
            $("input[type='checkbox'][name='_check_row']").prop("checked", false);
            $('#tabData01 tbody').find("tr").each(function () {
                $(this).removeClass("row__selected");
                // 设置删除按钮有效
                let _event_delete_onclick = '_Instance.DoDelete($(this))';
                $(this).children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
            });
            $("#CheckAll").prop("checked", false);
            ShowSuccessMessagePanel("权限回收成功。");
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function ($row, index) {
            // 设置删除按钮失效
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", "");
        }, function ($row, index) {
            // 设置删除按钮有效
            let _event_delete_onclick = '_Instance.DoDelete($(this))';
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divD1").offset().top;
        let _rc = Math.floor((h - _tabTop) / 25);
        let _dh = _rc * 25;
        let _tah = this.rows * 25;
        _dh = (_tah >= _dh) ? _dh : _tah;

        $("#divD1").css({"max-height": _dh, height: _dh});
    }
    SortTable(orderBy) {
        this.orderby = orderBy;
        // 得到排序数据
        this.FetchForPage(1);
    }
}

let _Instance = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    _Instance = new MyPage(0, null, null, null, null, null, null, null,
            "/master/mps_item/fetchAll.html",
            "/master/mps_item/delete.html");

    _Instance.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    if (_Instance !== null)
        _Instance.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
function CheckGridInput() {
    $('#tabData01 tbody').find("tr").each(function () {
        let $row = $(this);
        let _name = $.trim($(this).find('td').eq(3).text());   // 名

        if (_name === '') {
            GridCheckErrHandle($row, 3, '主产品计划项目名不能为空。');
        } else {
            GridCheckSuccessHandle($row, 3);
        }
    });
    if ($('#tabData01 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}